package com.zpb.portal.service.impl;

import com.zpb.framework.domain.ApiResult;
import com.zpb.framework.domain.entity.UserInfo;
import com.zpb.framework.domain.vo.LoginVo;
import com.zpb.framework.domain.vo.UserVo;
import com.zpb.portal.service.LoginService;
import com.zpb.framework.utils.BeanCopyUtil;
import com.zpb.framework.utils.JwtUtil;
import com.zpb.framework.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: zhaopengbo
 * @Date: 2025/9/11
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ApiResult<Map<String,Object>> login(LoginVo user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(authenticate == null){
            throw new RuntimeException("用户名或密码错误");
        }
        // 如果认证通过，使用userId生成一个jwt返回
        UserInfo userInfo = (UserInfo) authenticate.getPrincipal();
        Long userId = userInfo.getUser().getId();
        String jwt = JwtUtil.createJWT(userId.toString());
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        map.put("userInfo", BeanCopyUtil.copyBean(userInfo.getUser(), UserVo.class));
        // 把完整的用户信息存入Redis userId作为key
        redisCache.setCacheObject("blogLogin:"+userId,userInfo);
        return ApiResult.success(map,"登录成功");
    }

    @Override
    public ApiResult logout() {
        UsernamePasswordAuthenticationToken authentication = 
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserInfo userInfo = (UserInfo) authentication.getPrincipal();
        Long userId = userInfo.getUser().getId();
        redisCache.deleteObject("blogLogin:"+userId);
        return ApiResult.success();
    }
}
